<template>
    <base-breadcrumb v-loading="loading.page">
        <div class="about-master-container">
            <b-steps :current="stepVal" direction="vertical" @change.self="stepChange">
                <b-step title="基本信息">
                    <a-card v-show="activeKey[0]" slot="description" v-loading="loading.one" :bordered="false">
                        <a-form-model ref="ruleForm" :model="formData" :rules="rules">
                            <a-row>
                                <a-col span="8">
                                    <a-form-model-item label="物资检查记录编码">
                                        <BaseInput v-model="formData.code" disabled />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="检查地点" prop="checkPlaceId">
                                        <a-select v-model="formData.checkPlaceId" :disabled="state === 3" placeholder="请选择">
                                            <a-select-option v-for="item in addressArr" :key="item.id" :value="item.id">
                                                {{ item.name }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="检查单位">
                                        <BaseInput v-model="formData.checkOrgName" disabled />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col span="8">
                                    <a-form-model-item label="受检查单位" prop="inspectedUnitName">
                                        <a-input-search
                                            v-model="formData.inspectedUnitName"
                                            placeholder="请选择"
                                            :disabled="state === 3"
                                            @search="openCheckOrg"
                                            @click="openCheckOrg"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="检查时间" prop="checkDate">
                                        <a-date-picker
                                            v-model="formData.checkDate"
                                            value-format="YYYY-MM-DD"
                                            :disabled="state === 3"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="编号" prop="number">
                                        <BaseInput v-model="formData.number" :disabled="state === 3" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col span="8">
                                    <a-form-model-item label="优势点" prop="advantagePoint">
                                        <BaseInput v-model="formData.advantagePoint" :disabled="state === 3" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="改进点" prop="improvePoint">
                                        <BaseInput v-model="formData.improvePoint" :disabled="state === 3" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="其他补充说明">
                                        <BaseInput v-model="formData.otherSup" :disabled="state === 3" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col span="8">
                                    <a-form-model-item label="综合评价结论" prop="comEvalConclusionId">
                                        <a-select v-model="formData.comEvalConclusionId" :disabled="state === 3" placeholder="请选择">
                                            <a-select-option
                                                v-for="item in conclusionArr"
                                                :key="item.id"
                                                :value="item.id"
                                            >
                                                {{ item.name }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="受检查区域负责人" prop="inspectedRespEmployeeName">
                                        <a-input-search
                                            v-model="formData.inspectedRespEmployeeName"
                                            placeholder="请选择"
                                            :disabled="state === 3"
                                            @search="openHead"
                                            @click="openHead"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="陪同人">
                                        <a-select
                                            v-model="formData.escortIds"
                                            show-search
                                            mode="multiple"
                                            :disabled="state === 3"
                                            dropdown-class-name="select-scroll"
                                            @change="escortChange"
                                            @popupScroll="popupScroll"
                                            placeholder="请选择"
                                        >
                                            <a-select-option v-for="item in escortArr" :key="item.id" :value="item.id">
                                                {{ item.name }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col span="8">
                                    <a-form-model-item label="检查、记录人" prop="recorderName">
                                        <a-input-search
                                            v-model="formData.recorderName"
                                            placeholder="请选择"
                                            :disabled="state === 3"
                                            @search="openRecorder"
                                            @click="openRecorder"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="创建人">
                                        <BaseInput v-model="formData.creatorName" disabled />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="8">
                                    <a-form-model-item label="创建时间">
                                        <BaseInput v-model="formData.createTime" disabled />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </a-form-model>
                        <div class="pub-next-btn">
                            <a-button v-if="state !== 3" type="primary" @click="tempSave()"> 保存草稿 </a-button>
                            <a-button type="primary" @click="tempSave(true)"> 下一步 </a-button>
                        </div>
                    </a-card>
                </b-step>
                <b-step title="检查明细">
                    <a-card v-if="activeKey[1]" slot="description" :bordered="false">
                        <detail ref="detail" :state="state" :row="formData" />
                        <div class="pub-next-btn">
                            <a-button
                                v-if="state !== 3"
                                type="primary"
                                :loading="loading.isSaving"
                                @click="handleSaveDetail"
                            >
                                保存
                            </a-button>
                            <a-button type="primary" @click="previous"> 上一步 </a-button>
                            <a-button type="primary" :loading="loading.isSaving" @click="handleSaveDetail(next)">
                                下一步
                            </a-button>
                        </div>
                    </a-card>
                </b-step>
                <b-step title="相关附件">
                    <a-card v-if="activeKey[2]" slot="description" :bordered="false">
                        <u-table
                            :upload-list="addFile"
                            :delete-url="fileDel"
                            :is-show="state !== 3"
                            :list-url="fileList"
                            :business-id="formData.id"
                            business-code="MM17"
                        />
                        <div class="pub-next-btn">
                            <a-button type="primary" @click="previous"> 上一步 </a-button>
                        </div>
                    </a-card>
                </b-step>
            </b-steps>
            <div class="pub-header-btn page-btn-right-top">
                <a-button v-if="state !== 3" type="primary" :loading="loading.page" @click="submit"> 提交 </a-button>
                <a-button @click="handleClose"> 关闭 </a-button>
            </div>
            <org-list ref="orgInList" :org-code="orgCode" :other-data="otherData" @getOrg="getCheckOrg" />
            <person-list ref="headList" :other-data="{ rootOrgId: formData.inspectedUnitId }" @getPerson="getHead" />
            <person-list
                ref="recorderList"
                :other-data="{ rootOrgId: $currentSubCompany().companyId }"
                @getPerson="getRecorder"
            />
        </div>
    </base-breadcrumb>
</template>
<script>
import { getOrgUsers } from '@/api/commons'
import detail from '../components/detail/detail'
import { selectOption } from '@/api/material/goods/goods'
import {
    recordListAdd,
    recordListEdit,
    audit,
    addFile,
    fileList,
    fileDel,
    recordDetail
} from '@/api/material/check/record'

export default {
    name: 'a' + Date.now(),
    components: {
        detail
    },
    data() {
        return {
            activeKey: [true, false, false, false, false, false, false],
            loading: {
                isSaving: false,
                one: false,
                page: false
            },
            stepVal: 0,
            state: Number(this.$route.query.state),
            isSubmit: false,
            row: this.$route.query.row,
            formData: {
                createTime: this.getNowTime(),
                creatorName: '',
                code: '',
                checkPlaceId: void 0,
                checkOrgName: '',
                inspectedUnitName: '',
                checkDate: '',
                number: '',
                advantagePoint: '',
                improvePoint: '',
                otherSup: '',
                comEvalConclusionId: void 0,
                inspectedRespEmployeeName: '',
                escortIds: [],
                recorderName: '',
                inspectedUnitId: null,
                inspectedRespEmployeeId: '',
                recorderId: null,
                checkOrgId: ''
            },
            rules: {
                checkPlaceId: { required: true, message: '检查地点不能为空', trigger: 'change' },
                inspectedUnitName: { required: true, message: '受检查单位不能为空', trigger: 'change' },
                checkDate: { required: true, message: '检查时间不能为空', trigger: 'change' },
                number: { required: true, message: '编号不能为空', trigger: 'blur' },
                advantagePoint: { required: true, message: '优势点不能为空', trigger: 'blur' },
                improvePoint: { required: true, message: '改进点不能为空', trigger: 'blur' },
                comEvalConclusionId: { required: true, message: '综合评价结论不能为空', trigger: 'blur' },
                inspectedRespEmployeeName: { required: true, message: '受检查区域负责人不能为空', trigger: 'change' },
                escortIds: { required: true, message: '陪同人不能为空', trigger: 'blur' },
                recorderName: { required: true, message: '检查、记录人不能为空', trigger: 'change' }
            },
            isNext: false,
            addFile: addFile(),
            fileDel: fileDel(),
            fileList: fileList(),
            conclusionArr: [],
            addressArr: [],
            escortArr: [],
            pageSize: 10,
            pageNo: 1,
            totalPages: 0,
            userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),

            orgCode: '',
            otherData: null
        }
    },
    watch: {
        stepVal(newVal, oldVal) {
            this.$set(this.activeKey, newVal, true)
        }
    },
    mounted() {
        this.formData.checkOrgName = this.userInfo.currentPost.name
        this.formData.creatorName = this.userInfo.name
        this.formData.checkOrgId = this.userInfo.currentPost.id
        this.escortList({
            orgId: this.userInfo.orgId
        })
        this.getConclusion()
        this.getAddress()
        if (this.$route.query.id) {
            this.formData.id = this.$route.query.id
            this.getData()
            this.isSubmit = true
        }
    },
    methods: {
        handleSaveDetail(callback) {
            if (this.loading.isSaving) return
            if (this.state === 3) {
                this.next()
                return
            }
            this.loading.isSaving = true

            this.$refs.detail
                .submit()
                .then(() => {
                    this.loading.isSaving = false
                    this.formData.haveScore = true
                    callback && callback()
                })
                .catch(() => {
                    this.loading.isSaving = false
                })
        },
        async getData() {
            this.loading.one = true
            let res = await recordDetail({ id: this.formData.id })
            if (res.code === 200) {
                this.formData = { ...this.formData, ...res.data }
            }
            this.loading.one = false
        },
        async tempSave(isNext) {
            if (this.state === 3 && isNext) {
                this.next()
                return
            }
            this.$refs.ruleForm.validate(async (valid, object) => {
                if (valid) {
                    this.loading.one = true
                    if (this.formData.id) {
                        const res = await recordListEdit(this.formData)
                        if (res.code === 200) {
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            if (isNext) {
                                this.next()
                            }
                        }
                    } else {
                        const res = await recordListAdd(this.formData)
                        if (res.code === 200) {
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            this.formData.id = res.data.id
                            await this.getData()
                            if (isNext) {
                                this.next()
                            }
                        }
                    }
                    this.loading.one = false
                }
            })
        },

        handleClose() {
            this.$close()
        },
        previous() {
            this.isNext = true
            this.stepVal--
            if (this.stepVal < 0) {
                this.stepVal = 0
            }
        },
        popupScroll() {
            let element = document.getElementsByClassName('select-scroll')[0].firstChild.firstChild
            if (parseInt(element.scrollHeight - element.scrollTop) === element.clientHeight) {
                if (this.pageNo < this.totalPages) {
                    this.pageNo++
                    this.escortList()
                }
            }
        },
        async escortList(params) {
            let searchData = Object.assign(
                {
                    pageSize: this.pageSize,
                    pageNumber: this.pageNo
                },
                params,
                this.queryParam
            )
            let res = await getOrgUsers(searchData)
            this.escortArr = this.escortArr.concat(res.data)
        },
        escortChange(val) {},
        async getAddress() {
            let res = await selectOption({ type: 30 })
            if (res.code === 200) {
                this.addressArr = res.data
                //当创建人为公司人员时，枚举项为【分公司、项目部】；当创建人为分公司人员时，枚举项为【项目部】
                if (this.$userType() === 'BC') {
                    let index = this.addressArr.findIndex((v) => v.name === '分公司')
                    this.addressArr.splice(index, 1)
                    this.formData.checkPlaceId = this.addressArr[0].id
                }
            }
        },
        async getConclusion() {
            let res = await selectOption({ type: 31 })
            if (res.code === 200) {
                this.conclusionArr = res.data
            }
        },
        saveRectification() {
            this.$refs.rectificationResults.temporaryStorage()
        },
        saveAcceptance() {
            this.$refs.acceptance.temporaryStorage()
        },
        getCheckOrg(row) {
            this.formData.inspectedUnitName = row.name
            this.formData.inspectedUnitId = row.id
        },
        openCheckOrg() {
            if (this.formData.checkPlaceId) {
                if (this.$userType() === 'BC') {
                    this.otherData = { pid: this.$currentSubCompany().companyId, type: 3 }
                    this.orgCode = ''
                } else {
                    let org = this.addressArr.find((v) => v.id === this.formData.checkPlaceId)
                    if (org.name === '项目部') {
                        this.orgCode = 'PD'
                    } else {
                        this.orgCode = 'BC'
                    }
                    this.otherData = null
                }
                this.$refs.orgInList.open()
            } else {
                this.$noticeWarning('请选择检查地点')
            }
        },
        openHead() {
            this.$refs.headList.open()
        },
        getHead(row) {
            this.formData.inspectedRespEmployeeName = row.name
            this.formData.inspectedRespEmployeeId = row.id
        },
        openRecorder() {
            this.$refs.recorderList.open()
        },
        getRecorder(row) {
            this.formData.recorderName = row.name
            this.formData.recorderId = row.id
        },
        stepChange(val) {
            if (!this.formData.id) {
                if (val) {
                    this.$message.warning('切换步骤前请先填写基本信息')
                    this.stepVal = 0
                }
            } else {
                if (!this.isNext) {
                    this.$set(this.activeKey, val, !this.activeKey[val])
                }
            }
            this.isNext = false
        },
        async submit() {
            if (this.isSubmit) {
                this.$submitConfirm(async () => {
                    this.loading.page = true
                    let res = await audit({ baseId: this.formData.id, auditStatus: this.formData.auditStatus })
                    this.$message.success('提交成功')
                    this.$router.push({ path: '/material/check/record' })
                    this.loading.page = false
                })
            } else {
                this.$message.warning('提交之前请先暂存')
            }
        },
        next(val) {
            this.isNext = true
            this.stepVal++
        }
    }
}
</script>
